package com.sann.spring.service.impl;

import com.sann.spring.beans.Account;
import com.sann.spring.dao.IAccountDao;
import com.sann.spring.service.IAccountService;
import com.sann.spring.util.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 该Service层的逻辑在前一个基础上移除了事务逻辑，代码变得很清爽。
 * 事务管理器对象TransactionManager不用注入到Service层，而是注入到产生Service层代理对象的BeanFactory中。
 */
@Service(value="accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        List<Account> accounts = this.accountDao.findAllAccount();
        return accounts;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        Account account = this.accountDao.findAccountById(accountId);
        return account;
    }

    @Override
    public void saveAccount(Account account) {
        this.accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        this.accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccount(Integer accountId) {
        this.accountDao.deleteAccount(accountId);
    }

    /**
     * 转账
     * @param sourceName 转出账户名称
     * @param targetName 转入账户名称
     * @param money 转账金额
     */
    @Override
    public void transfer(String sourceName, String targetName, float money) {
        //2.1.查询转出账户
        Account source = accountDao.findByName(sourceName);
        //2.2.查询转入账户
        Account target = accountDao.findByName(targetName);
        //2.3.转出账户减钱
        source.setMoney(source.getMoney() - money);
        //2.4.转入账户加钱
        target.setMoney(target.getMoney() + money);
        //2.5.更新转出账户
        accountDao.updateAccount(source);

        // 引入出现业务异常逻辑
        int i = 1/0;

        //2.6.更新转入账户
        accountDao.updateAccount(target);
    }

}
